const { app, BrowserWindow, ipcMain, dialog, screen, desktopCapturer } = require('electron')
const path = require('path')
const { nativeImage } = require('electron')

let mainWindow = null
let colorPickerWindow = null
let isColorPicking = false
let colorPickingInterval = null
let lastScreenshot = null
let lastScreenshotTime = 0
const SCREENSHOT_CACHE_TIME = 16 // 缓存16ms，约60fps

function createWindow () {
  // 创建浏览器窗口
  mainWindow = new BrowserWindow({
    width: 900,
    height: 800,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  })

  // 加载 index.html
  mainWindow.loadFile('index.html')

  // 打开开发工具（可选）
  // mainWindow.webContents.openDevTools()
}

// 处理文件选择请求
ipcMain.handle('select-file', async () => {
  const window = BrowserWindow.getFocusedWindow() || mainWindow
  const result = await dialog.showOpenDialog(window, {
    properties: ['openFile'],
    filters: [
      { name: '所有文件', extensions: ['*'] },
      { name: '文本文件', extensions: ['txt', 'md', 'json'] },
      { name: '图片文件', extensions: ['jpg', 'jpeg', 'png', 'gif', 'bmp'] },
      { name: '视频文件', extensions: ['mp4', 'avi', 'mov', 'mkv'] }
    ]
  })
  
  if (!result.canceled && result.filePaths.length > 0) {
    return {
      success: true,
      filePath: result.filePaths[0]
    }
  }
  
  return {
    success: false,
    filePath: null
  }
})

// 打开颜色拾取器窗口
function createColorPickerWindow() {
  if (colorPickerWindow) {
    colorPickerWindow.focus()
    return
  }
  
  colorPickerWindow = new BrowserWindow({
    width: 900,
    height: 600,
    title: '数码测色计',
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  })
  
  colorPickerWindow.loadFile('color-picker.html')
  
  colorPickerWindow.on('closed', () => {
    colorPickerWindow = null
    if (isColorPicking) {
      stopColorPicking()
    }
  })
}

// 获取鼠标位置的颜色
async function getColorAtPosition(x, y) {
  try {
    const displays = screen.getAllDisplays()
    const primaryDisplay = screen.getPrimaryDisplay()
    
    // 获取屏幕截图
    const screenshot = await desktopCapturer.getSources({
      types: ['screen'],
      thumbnailSize: { width: primaryDisplay.size.width, height: primaryDisplay.size.height }
    })
    
    if (screenshot.length === 0) {
      return null
    }
    
    // 使用 nativeImage 处理截图
    const image = nativeImage.createFromDataURL(screenshot[0].thumbnail.toDataURL())
    const imgBuffer = image.getBitmap()
    
    // 计算像素位置（需要考虑缩放）
    const scaleFactor = primaryDisplay.scaleFactor
    const pixelX = Math.floor(x * scaleFactor)
    const pixelY = Math.floor(y * scaleFactor)
    
    // 获取像素颜色（简化版本，实际需要更复杂的处理）
    // 这里我们使用屏幕 API 的另一种方法
    return await getPixelColor(x, y)
  } catch (error) {
    console.error('获取颜色失败:', error)
    return null
  }
}

// 使用屏幕 API 获取像素颜色
async function getPixelColor(x, y) {
  try {
    const displays = screen.getAllDisplays()
    const primaryDisplay = screen.getPrimaryDisplay()
    
    // 获取整个屏幕的截图
    const screenshot = await desktopCapturer.getSources({
      types: ['screen'],
      thumbnailSize: primaryDisplay.size
    })
    
    if (screenshot.length === 0) {
      return null
    }
    
    const image = nativeImage.createFromDataURL(screenshot[0].thumbnail.toDataURL())
    const size = image.getSize()
    
    // 计算实际像素位置
    const scaleFactor = primaryDisplay.scaleFactor
    const pixelX = Math.floor(x * scaleFactor)
    const pixelY = Math.floor(y * scaleFactor)
    
    // 获取像素数据（需要转换为 canvas 来读取像素）
    // 这里返回一个模拟的颜色值，实际实现需要使用 canvas
    return { r: 128, g: 128, b: 128 }
  } catch (error) {
    console.error('获取像素颜色失败:', error)
    return null
  }
}

// 获取屏幕截图（带缓存）
async function getScreenshot() {
  const now = Date.now()
  
  // 如果缓存有效，直接返回
  if (lastScreenshot && (now - lastScreenshotTime) < SCREENSHOT_CACHE_TIME) {
    return lastScreenshot
  }
  
  try {
    const primaryDisplay = screen.getPrimaryDisplay()
    const { width, height } = primaryDisplay.size
    
    // 获取屏幕截图
    const sources = await desktopCapturer.getSources({
      types: ['screen'],
      thumbnailSize: { width, height }
    })
    
    if (sources.length > 0) {
      const screenshot = sources[0].thumbnail.toDataURL()
      lastScreenshot = screenshot
      lastScreenshotTime = now
      return screenshot
    }
  } catch (error) {
    console.error('获取截图失败:', error)
  }
  
  return lastScreenshot || null
}

// 开始颜色拾取
ipcMain.on('start-color-picking', () => {
  if (isColorPicking) return
  
  isColorPicking = true
  lastScreenshot = null
  lastScreenshotTime = 0
  
  // 使用更短的间隔提升灵敏度（约60fps）
  colorPickingInterval = setInterval(async () => {
    if (!isColorPicking || !colorPickerWindow) return
    
    try {
      const point = screen.getCursorScreenPoint()
      const screenshot = await getScreenshot()
      
      if (screenshot && colorPickerWindow) {
        // 发送颜色数据到渲染进程
        colorPickerWindow.webContents.send('color-data', {
          x: point.x,
          y: point.y,
          screenshot: screenshot,
          timestamp: Date.now()
        })
      }
    } catch (error) {
      console.error('颜色拾取错误:', error)
    }
  }, 16) // 每 16ms 更新一次（约60fps）
})

// 停止颜色拾取
ipcMain.on('stop-color-picking', () => {
  stopColorPicking()
})

function stopColorPicking() {
  isColorPicking = false
  if (colorPickingInterval) {
    clearInterval(colorPickingInterval)
    colorPickingInterval = null
  }
  // 清空缓存
  lastScreenshot = null
  lastScreenshotTime = 0
}

// 处理打开颜色拾取器的请求
ipcMain.handle('open-color-picker', () => {
  createColorPickerWindow()
})

// 当 Electron 完成初始化时创建窗口
app.whenReady().then(() => {
  createWindow()
  
  // 添加菜单项打开颜色拾取器
  const { Menu } = require('electron')
  const template = [
    {
      label: '工具',
      submenu: [
        {
          label: '数码测色计',
          click: () => {
            createColorPickerWindow()
          }
        }
      ]
    }
  ]
  const menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)

  app.on('activate', function () {
    // 在 macOS 上，当点击 dock 图标并且没有其他窗口打开时，
    // 通常会在应用程序中重新创建一个窗口
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// 当所有窗口都被关闭时退出应用
app.on('window-all-closed', function () {
  // 在 macOS 上，应用通常会保持活动状态，直到用户明确退出
  if (process.platform !== 'darwin') app.quit()
})

